package com.cdshangpai.utils.api;

import android.text.TextUtils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cdshangpai.utils.db.beans.Aboutus;
import com.cdshangpai.utils.db.beans.Account;
import com.cdshangpai.utils.db.beans.Case;
import com.cdshangpai.utils.db.beans.Form;
import com.cdshangpai.utils.db.beans.Hotal;
import com.cdshangpai.utils.db.beans.Video;
import com.cdshangpai.utils.offlinecache.DbVersion;
import com.cdshangpai.utils.offlinecache.VersionBean;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

import lombok.Data;


/**
 * 服务器接口
 */
public class Api {
    private static OkHttpClient okHttpClient=new OkHttpClient();
    private static OkHttpClient getOkHttpClient()
    {
        okHttpClient.setConnectTimeout(NetConfig.connectTimeout, TimeUnit.SECONDS);
        okHttpClient.setReadTimeout(NetConfig.readTimeout,TimeUnit.SECONDS);
        return okHttpClient;
    }


    /*private static String host="http://192.168.1.2:8086/api/photoapp/";
    private static String queryDbVersionUrl=host+"getversion";
    private static String queryCaseUrl=host+"querycases";
    private static String queryHotalUrl=host+"queryhotals";
    private static String queryVideoUrl=host+"queryvideos";
    private static String queryAccountUrl=host+"queryaccounts";
    private static String queryAboutusUrl=host+"queryaboutus";
    private static String formSubmitUrl="";*/

    public static String imagehost="http://tandan.choco.com.cn";
    private static String host="http://tandan.choco.com.cn/api/";
    private static String queryDbVersionUrl=host+"alldata";
    private static String queryCaseUrl=host+"cases_api";
    private static String queryHotalUrl=host+"hotal_api";
    private static String queryVideoUrl=host+"video_api";
    private static String queryAccountUrl=host+"account_api";
    private static String queryAboutusUrl=host+"service_api";
    private static String formSubmitUrl=host+"message_api";

    /**
     * 查询服务器数据
     * @return
     */
    public VersionBean queryDbVersion()
    {
        VersionBean result=null;
        Request request = new Request.Builder().url(queryDbVersionUrl).build();
        try {
            Response response = getOkHttpClient().newCall(request).execute();
            if(response.isSuccessful())
            {
                String respData=response.body().string();
                result=parseDbVersionData(respData);
            }
        }catch (Exception e)
        {}
        return result;
    }

    /**
     * 查询案例数据
     * @return
     */
    public List<Case> queryCase(List<Integer> caseIds)
    {
        LinkedBlockingQueue<String> queue=new LinkedBlockingQueue<>();
        HttpQueueCallback httpQueueCallback=new HttpQueueCallback(queue);
        HttpResponse httpResponse=new HttpResponse(null,httpQueueCallback,String.class);

//        String ids= StringUtils.join(ArrayUtils.toArray(caseIds),",");
        IdParam idParam=new IdParam();
        idParam.setIds(caseIds);
        HttpRequest.instance.post(queryCaseUrl,idParam,httpResponse);

        String response=null;
        try
        {
            response=queue.take();
        }catch (Exception e){
            return null;
        }
        if(TextUtils.isEmpty(response))
        {
            return null;
        }else
        {
            return parseCase(response);
        }
    }

    /**
     * 查询服务器酒店数据
     * @param hotalIds
     * @return
     */
    public List<Hotal> queryHotal(List<Integer> hotalIds)
    {
        LinkedBlockingQueue<String> queue=new LinkedBlockingQueue<>();
        HttpQueueCallback httpQueueCallback=new HttpQueueCallback(queue);
        HttpResponse httpResponse=new HttpResponse(null,httpQueueCallback,String.class);

//        String ids= StringUtils.join(ArrayUtils.toArray(hotalIds),",");
        IdParam idParam=new IdParam();
        idParam.setIds(hotalIds);
        HttpRequest.instance.post(queryHotalUrl,idParam,httpResponse);

        String response=null;
        try
        {
            response=queue.take();
        }catch (Exception e){
            return null;
        }
        if(TextUtils.isEmpty(response))
        {
            return null;
        }else
        {
            return parseHotal(response);
        }
    }

    /**
     * 查询服务器视频数据
     * @param videoIds
     * @return
     */
    public List<Video> queryVideo(List<Integer> videoIds)
    {
        LinkedBlockingQueue<String> queue=new LinkedBlockingQueue<>();
        HttpQueueCallback httpQueueCallback=new HttpQueueCallback(queue);
        HttpResponse httpResponse=new HttpResponse(null,httpQueueCallback,String.class);

//        String ids= StringUtils.join(ArrayUtils.toArray(videoIds),",");
        IdParam idParam=new IdParam();
        idParam.setIds(videoIds);
        HttpRequest.instance.post(queryVideoUrl,idParam,httpResponse);

        String response=null;
        try
        {
            response=queue.take();
        }catch (Exception e){
            return null;
        }
        if(TextUtils.isEmpty(response))
        {
            return null;
        }else
        {
            return parseVideo(response);
        }
    }

    /**
     * 查询服务器账号数据
     * @return
     */
    public List<Account> queryAccount(List<Integer> accountIds)
    {
        LinkedBlockingQueue<String> queue=new LinkedBlockingQueue<>();
        HttpQueueCallback httpQueueCallback=new HttpQueueCallback(queue);
        HttpResponse httpResponse=new HttpResponse(null,httpQueueCallback,String.class);

//        String ids= StringUtils.join(ArrayUtils.toArray(videoIds),",");
        IdParam idParam=new IdParam();
        idParam.setIds(accountIds);

        HttpRequest.instance.post(queryAccountUrl,idParam,httpResponse);

        String response=null;
        try
        {
            response=queue.take();
        }catch (Exception e){
            return null;
        }
        if(response==null)
        {
            return null;
        }else
        {
            return parseAccount(response);
        }
        /*Request request = new Request.Builder().url(queryAccountUrl).build();
        try {
            Response response = okHttpClient.newCall(request).execute();
            if(response.isSuccessful())
            {
                String respData=response.body().string();
                List<Account>result=parseAccount(respData);
                return result;
            }
        }catch (Exception e)
        {}
        return null;*/
    }

    /**
     * 查询关于我们数据
     * @return
     */
    public Aboutus queryAboutus()
    {
        Request request = new Request.Builder().url(queryAboutusUrl).build();
        try {
            Response response = okHttpClient.newCall(request).execute();
            if(response.isSuccessful())
            {
                String respData=response.body().string();
                Aboutus result=parseAboutus(respData);
                return result;
            }
        }catch (Exception e)
        {}
        return null;
    }

    /**
     * 提交表单到服务器
     * @param forms
     * @return
     */
    public boolean submitForm(ArrayList<Form> forms)
    {
        LinkedBlockingQueue<String> queue=new LinkedBlockingQueue<>();
        HttpQueueCallback httpQueueCallback=new HttpQueueCallback(queue);
        HttpResponse httpResponse=new HttpResponse(null,httpQueueCallback,String.class);

        FormParam datas=convert2submitForm(forms);
        HttpRequest.instance.post(formSubmitUrl,datas,httpResponse);

        String response=null;
        try
        {
            response=queue.take();
        }catch (Exception e){}
        if(response==null)
        {
            return false;
        }else if(response.indexOf("ok")>=0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    /**
     * 数据库表单列表转提交格式表单列表
     * @param forms
     * @return
     */
    private FormParam convert2submitForm(List<Form> forms)
    {
        FormParam formParam=new FormParam();
        formParam.forms=new ArrayList<>();
        for(Form form:forms)
        {
            SubmitForm item=new SubmitForm();
            item.id=form.id;
            item.accountid=form.accountid;
            item.name=form.name;
            item.phone=form.phone;
            item.remark=form.remark;
            item.caseids=convert2List(form.caseids);
            item.videoids=convert2List(form.videoids);
            formParam.forms.add(item);
        }
        return formParam;
    }

    /**
     * 表单提交数据
     */
    @Data
    public class FormParam
    {
        List<SubmitForm> forms;
    }

    /**
     * 提交格式表单
     */
    @Data
    public class SubmitForm{
        public Integer id;
        public Integer accountid;
        public String name;
        public String phone;
        public String remark;
        public List<Integer> caseids;
        public List<Integer> videoids;
    }

    /**
     * “1，2，3”格式转List<Integer>
     * @param array
     * @return
     */
    private List<Integer> convert2List(String array)
    {
        List<Integer> result=new ArrayList<>();
        if(!TextUtils.isEmpty(array))
        {
            String[] arr=array.split(",");
            for(String item:arr) {
                result.add(Integer.parseInt(item));
            }
        }
        return result;
    }

    /**
     * 分析服务器接口返回的数据库返回数据
     * @param response
     * @return
     */
    private VersionBean parseDbVersionData(String response)
    {
        VersionBean versionBean=new VersionBean();
        JSONObject respObject=JSONObject.parseObject(response);



        List<DbVersion> cases=new ArrayList<>();
        if(respObject.containsKey("cases")) {
            JSONArray caseArray = respObject.getJSONArray("cases");
            if(caseArray!=null) {
                for (int i = 0; i < caseArray.size(); i++) {
                    JSONObject item = caseArray.getJSONObject(i);
                    DbVersion cas = new DbVersion();
//            cas.id=item.getInteger("id");
                    cas.id = Integer.parseInt(item.get("id").toString());
                    cas.version = item.getString("version");
                    cases.add(cas);
                }
            }
        }
        versionBean.cases=cases;

        List<DbVersion> hotals=new ArrayList<>();
        if(respObject.containsKey("hotals")) {
            JSONArray hotalArray = respObject.getJSONArray("hotals");
            if(hotalArray!=null) {
                for (int i = 0; i < hotalArray.size(); i++) {
                    JSONObject item = hotalArray.getJSONObject(i);
                    DbVersion hotal = new DbVersion();
//            hotal.id=item.getInteger("id");
                    hotal.id = Integer.parseInt(item.get("id").toString());
                    hotal.version = item.getString("version");
                    hotals.add(hotal);
                }
            }
        }
        versionBean.holtals=hotals;

        List<DbVersion> videos=new ArrayList<>();
        if(respObject.containsKey("videos")) {
            JSONArray videoArray = respObject.getJSONArray("videos");
            if(videoArray!=null) {
                for (int i = 0; i < videoArray.size(); i++) {
                    JSONObject item = videoArray.getJSONObject(i);
                    DbVersion video = new DbVersion();
//            video.id=item.getInteger("id");
                    video.id = Integer.parseInt(item.get("id").toString());
                    video.version = item.getString("version");
                    videos.add(video);
                }
            }
        }
        versionBean.videos=videos;

        List<DbVersion> accounts=new ArrayList<>();
        if(respObject.containsKey("accounts")) {
            JSONArray accountArray = respObject.getJSONArray("accounts");
            if(accountArray!=null) {
                for (int i = 0; i < accountArray.size(); i++) {
                    JSONObject item = accountArray.getJSONObject(i);
                    DbVersion account = new DbVersion();
//            account.id=item.getInteger("id");
                    account.id = Integer.parseInt(item.get("id").toString());
                    account.version = item.getString("version");
                    accounts.add(account);
                }
            }
        }
        versionBean.accounts=accounts;

        DbVersion aboutus=null;
        if(respObject.containsKey("aboutus")) {
            JSONObject aboutusObj = respObject.getJSONObject("aboutus");
            if(aboutusObj!=null) {
                aboutus = new DbVersion();
                aboutus.id = Integer.parseInt(aboutusObj.get("id").toString());
                aboutus.version = aboutusObj.getString("version");
            }
        }
        versionBean.aboutus=aboutus;

        return versionBean;
    }

    /**
     * 解析服务器返回的案例数据
     * @param response
     * @return
     */
    private List<Case> parseCase(String response)
    {
        JSONArray caseArray=JSONArray.parseArray(response);
        List<Case> cases=new ArrayList<>();
        for(int i=0;i<caseArray.size();i++)
        {
            JSONObject item=caseArray.getJSONObject(i);
            Case cas=new Case();
            cas.id=item.getInteger("id");
            cas.index=item.containsKey("index")?item.getLong("index"):0L;
            cas.title=item.getString("title");
            cas.city=item.getString("city");
            cas.style=item.getString("style");
            cas.color=item.getString("color");
            cas.price=item.getString("price");
            cas.area=item.getString("area");
            cas.content=item.getString("content");
            cas.hotalid=item.getInteger("hotalid");
            cas.hotal=item.getString("hotal");
            cas.version=item.getString("version");
            cas.titleimgUrl=item.getString("titleimgurl");
            cas.photosUrl=item.getString("photourls");
            cases.add(cas);
        }
        return cases;
    }

    /**
     * 解析服务器返回的酒店数据
     * @param response
     * @return
     */
    private List<Hotal> parseHotal(String response)
    {
        JSONArray hotalArray=JSONArray.parseArray(response);
        List<Hotal> hotals=new ArrayList<>();
        for(int i=0;i<hotalArray.size();i++)
        {
            JSONObject item=hotalArray.getJSONObject(i);
            Hotal hotal=new Hotal();
            hotal.id=item.getInteger("id");
            hotal.index=item.containsKey("index")?item.getLong("index"):0L;
            hotal.name=item.getString("name");
            hotal.city=item.getString("city");
            hotal.content=item.getString("content");
            hotal.version=item.getString("version");
            hotal.titleimgUrl=item.getString("titleimgurl");
            hotal.photosUrl=item.getString("photourls");
            hotals.add(hotal);
        }
        return hotals;
    }

    /**
     * 解析服务器返回的视频数据
     * @param response
     * @return
     */
    private List<Video> parseVideo(String response)
    {
        JSONArray videoArray=JSONArray.parseArray(response);
        List<Video> videos=new ArrayList<>();
        for(int i=0;i<videoArray.size();i++)
        {
            JSONObject item=videoArray.getJSONObject(i);
            Video video=new Video();
            video.id=item.getInteger("id");
            video.index=item.containsKey("index")?item.getLong("index"):0L;
            video.title=item.getString("title");
            video.titleimgUrl=item.getString("titleimgurl");
            video.videoUrl=item.getString("videourl");
            video.version=item.getString("version");
            videos.add(video);
        }
        return videos;
    }

    /**
     * 分析账号数据
     * @param response
     * @return
     */
    private List<Account> parseAccount(String response)
    {
        JSONArray accountArray=JSONArray.parseArray(response);
        List<Account> accounts=new ArrayList<>();
        for(int i=0;i<accountArray.size();i++)
        {
            JSONObject item=accountArray.getJSONObject(i);
            Account account=new Account();
            account.id=item.getInteger("id");
            account.account=item.getString("account");
            account.password=item.getString("password");
            account.name=item.getString("name");
            account.area=item.getString("area");
            account.version=item.getString("version");
            accounts.add(account);
        }
        return accounts;
    }

    /**
     * 分析关于我们数据
     * @param response
     * @return
     */
    private Aboutus parseAboutus(String response)
    {
        JSONObject aboutusObject=JSONObject.parseObject(response);
        Aboutus aboutus=new Aboutus();
        aboutus.id=1;
//        aboutus.id=aboutusObject.getInteger("id");
        aboutus.area=aboutusObject.getString("area");
        aboutus.content=aboutusObject.getString("homephotocaseid");//作为案例id列表使用
        aboutus.version=aboutusObject.getString("version");
        aboutus.homephotoUrls=aboutusObject.getString("homephotourls");
        aboutus.letterphotoUrls=aboutusObject.getString("photourls1");
        aboutus.photoUrls=aboutusObject.getString("photourls2");
        aboutus.ideaphotoUrls=aboutusObject.getString("photourls3");
        aboutus.servicephotoUrls=aboutusObject.getString("photourls4");
        aboutus.processphotoUrls=aboutusObject.getString("photourls5");
        aboutus.advantagephotoUrls=aboutusObject.getString("photourls6");
        aboutus.casephotoUrls=aboutusObject.getString("photourls7");
        aboutus.chargesphotoUrls=aboutusObject.getString("photourls8");
        aboutus.promotionphotoUrls=aboutusObject.getString("photourls9");
        aboutus.documentphotoUrls=aboutusObject.getString("photourls10");
        return aboutus;
    }
}
